import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { 
  Typography, 
  Button, 
  Card, 
  Table, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Tag, 
  message,
  Popconfirm,
  Row,
  Col,
  Statistic,
  Empty
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  PlayCircleOutlined, 
  CopyOutlined,
  FolderOpenOutlined,
  VideoCameraOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { 
  StoryboardProject, 
  StoryboardProjectStatus,
  StoryboardProjectTemplate,
  CreateStoryboardProjectParams
} from '../../../types/storyboardProject'
import { storyboardProjectService } from '../../../services/storage/storyboardProjectService'

const { Title, Paragraph } = Typography
const { TextArea } = Input

/**
 * 分镜管理页面组件
 * 分镜项目的创建、编辑和管理功能
 * 最后更新: 2025-10-23
 */
const StoryboardPage: React.FC = () => {
  const navigate = useNavigate()
  const [projects, setProjects] = useState<StoryboardProject[]>([])
  const [loading, setLoading] = useState(false)
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [currentProject, setCurrentProject] = useState<StoryboardProject | null>(null)
  const [form] = Form.useForm()

  // 加载项目列表
  const loadProjects = async () => {
    setLoading(true)
    try {
      const projectList = await storyboardProjectService.getProjects({
        sortBy: 'updatedAt',
        sortOrder: 'desc'
      })
      setProjects(projectList)
    } catch (error) {
      console.error('[分镜管理] 加载项目失败:', error)
      message.error('加载项目列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 组件初始化时加载项目
  useEffect(() => {
    console.log('[分镜管理] 组件初始化，开始加载项目列表')
    loadProjects()
  }, [])

  // 状态标签颜色映射
  const getStatusColor = (status: StoryboardProjectStatus): string => {
    const colorMap = {
      [StoryboardProjectStatus.DRAFT]: 'default',
      [StoryboardProjectStatus.IN_PROGRESS]: 'processing',
      [StoryboardProjectStatus.COMPLETED]: 'success',
      [StoryboardProjectStatus.ARCHIVED]: 'warning'
    }
    return colorMap[status] || 'default'
  }

  // 状态文本映射
  const getStatusText = (status: StoryboardProjectStatus): string => {
    const textMap = {
      [StoryboardProjectStatus.DRAFT]: '草稿',
      [StoryboardProjectStatus.IN_PROGRESS]: '进行中',
      [StoryboardProjectStatus.COMPLETED]: '已完成',
      [StoryboardProjectStatus.ARCHIVED]: '已归档'
    }
    return textMap[status] || '未知'
  }

  // 模板文本映射
  const getTemplateText = (template: StoryboardProjectTemplate): string => {
    const textMap = {
      [StoryboardProjectTemplate.BLANK]: '空白项目',
      [StoryboardProjectTemplate.SHORT_VIDEO]: '短视频',
      [StoryboardProjectTemplate.COMMERCIAL]: '广告',
      [StoryboardProjectTemplate.DOCUMENTARY]: '纪录片',
      [StoryboardProjectTemplate.SHORT_FILM]: '微电影'
    }
    return textMap[template] || '未知'
  }

  // 创建项目
  const handleCreateProject = async (values: any) => {
    try {
      const params: CreateStoryboardProjectParams = {
        ...values,
        tags: values.tags ? values.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean) : []
      }
      await storyboardProjectService.createProject(params)
      message.success('项目创建成功')
      setCreateModalVisible(false)
      form.resetFields()
      loadProjects()
    } catch (error) {
      console.error('[分镜管理] 创建项目失败:', error)
      message.error('创建项目失败')
    }
  }

  // 编辑项目
  const handleEditProject = async (values: any) => {
    if (!currentProject) return
    
    try {
      const updateParams = {
        ...values,
        tags: values.tags ? values.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean) : []
      }
      await storyboardProjectService.updateProject(currentProject.id, updateParams)
      message.success('项目更新成功')
      setEditModalVisible(false)
      form.resetFields()
      setCurrentProject(null)
      loadProjects()
    } catch (error) {
      console.error('[分镜管理] 更新项目失败:', error)
      message.error('更新项目失败')
    }
  }

  // 删除项目
  const handleDeleteProject = async (projectId: string) => {
    try {
      await storyboardProjectService.deleteProject(projectId)
      message.success('项目删除成功')
      loadProjects()
    } catch (error) {
      console.error('[分镜管理] 删除项目失败:', error)
      message.error('删除项目失败')
    }
  }

  // 复制项目
  const handleDuplicateProject = async (projectId: string) => {
    try {
      await storyboardProjectService.duplicateProject(projectId)
      message.success('项目复制成功')
      loadProjects()
    } catch (error) {
      console.error('[分镜管理] 复制项目失败:', error)
      message.error('复制项目失败')
    }
  }

  // 打开编辑对话框
  const openEditModal = (project: StoryboardProject) => {
    setCurrentProject(project)
    form.setFieldsValue({
      name: project.name,
      description: project.description,
      status: project.status,
      tags: project.tags?.join(', ')
    })
    setEditModalVisible(true)
  }

  // 表格列定义
  const columns: ColumnsType<StoryboardProject> = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: StoryboardProject) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          {record.description && (
            <div style={{ color: '#666', fontSize: '12px', marginTop: '4px' }}>
              {record.description}
            </div>
          )}
        </div>
      )
    },
    {
      title: '模板',
      dataIndex: 'template',
      key: 'template',
      width: 100,
      render: (template: StoryboardProjectTemplate) => getTemplateText(template)
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: StoryboardProjectStatus) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '场景数',
      dataIndex: ['stats', 'sceneCount'],
      key: 'sceneCount',
      width: 80,
      render: (count: number) => count || 0
    },
    {
      title: '时长',
      dataIndex: ['stats', 'totalDuration'],
      key: 'totalDuration',
      width: 80,
      render: (duration: number) => `${duration || 0}秒`
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 120,
      render: (time: string) => new Date(time).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record: StoryboardProject) => (
        <Space size="small">
          <Button 
            size="small" 
            icon={<PlayCircleOutlined />}
            onClick={() => {
              console.log('点击编辑按钮，项目ID:', record.id)
              console.log('跳转路径:', `/storyboard/project/${record.id}`)
              navigate(`/storyboard/project/${record.id}`)
            }}
          >
            编辑
          </Button>
          <Button 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            设置
          </Button>
          <Button 
            size="small" 
            icon={<CopyOutlined />}
            onClick={() => handleDuplicateProject(record.id)}
          >
            复制
          </Button>
          <Popconfirm
            title="确认删除此项目吗？"
            description="删除后无法恢复，请谨慎操作。"
            onConfirm={() => handleDeleteProject(record.id)}
            okText="删除"
            cancelText="取消"
            okType="danger"
          >
            <Button 
              size="small" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 统计信息
  const stats = {
    total: projects.length,
    draft: projects.filter(p => p.status === StoryboardProjectStatus.DRAFT).length,
    inProgress: projects.filter(p => p.status === StoryboardProjectStatus.IN_PROGRESS).length,
    completed: projects.filter(p => p.status === StoryboardProjectStatus.COMPLETED).length
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和统计 */}
      <div style={{ marginBottom: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '16px' }}>
          <div>
            <Title level={2}>分镜管理</Title>
            <Paragraph type="secondary">
              管理分镜项目，创建和编辑分镜脚本
            </Paragraph>
          </div>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            size="large"
            onClick={() => setCreateModalVisible(true)}
          >
            新建项目
          </Button>
        </div>

        {/* 统计卡片 */}
        <Row gutter={16}>
          <Col span={6}>
            <Card>
              <Statistic title="总项目数" value={stats.total} prefix={<VideoCameraOutlined />} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="草稿" value={stats.draft} valueStyle={{ color: '#666' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="进行中" value={stats.inProgress} valueStyle={{ color: '#1890ff' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="已完成" value={stats.completed} valueStyle={{ color: '#52c41a' }} />
            </Card>
          </Col>
        </Row>
      </div>

      {/* 项目列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={projects}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 个项目`
          }}
          locale={{
            emptyText: (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="暂无分镜项目"
              >
                <Button type="primary" onClick={() => setCreateModalVisible(true)}>
                  创建第一个项目
                </Button>
              </Empty>
            )
          }}
        />
      </Card>

      {/* 创建项目对话框 */}
      <Modal
        title="新建分镜项目"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false)
          form.resetFields()
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateProject}
        >
          <Form.Item
            label="项目名称"
            name="name"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input placeholder="输入项目名称" />
          </Form.Item>

          <Form.Item
            label="项目描述"
            name="description"
          >
            <TextArea 
              placeholder="输入项目描述（可选）"
              rows={3}
            />
          </Form.Item>

          <Form.Item
            label="项目模板"
            name="template"
            rules={[{ required: true, message: '请选择项目模板' }]}
            initialValue={StoryboardProjectTemplate.BLANK}
          >
            <Select>
              <Select.Option value={StoryboardProjectTemplate.BLANK}>
                空白项目
              </Select.Option>
              <Select.Option value={StoryboardProjectTemplate.SHORT_VIDEO}>
                短视频模板
              </Select.Option>
              <Select.Option value={StoryboardProjectTemplate.COMMERCIAL}>
                广告模板
              </Select.Option>
              <Select.Option value={StoryboardProjectTemplate.DOCUMENTARY}>
                纪录片模板
              </Select.Option>
              <Select.Option value={StoryboardProjectTemplate.SHORT_FILM}>
                微电影模板
              </Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="项目标签"
            name="tags"
          >
            <Input placeholder="输入标签，用逗号分隔（可选）" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setCreateModalVisible(false)
                form.resetFields()
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                创建项目
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑项目对话框 */}
      <Modal
        title="编辑项目信息"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false)
          form.resetFields()
          setCurrentProject(null)
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleEditProject}
        >
          <Form.Item
            label="项目名称"
            name="name"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input placeholder="输入项目名称" />
          </Form.Item>

          <Form.Item
            label="项目描述"
            name="description"
          >
            <TextArea 
              placeholder="输入项目描述（可选）"
              rows={3}
            />
          </Form.Item>

          <Form.Item
            label="项目状态"
            name="status"
            rules={[{ required: true, message: '请选择项目状态' }]}
          >
            <Select>
              <Select.Option value={StoryboardProjectStatus.DRAFT}>
                草稿
              </Select.Option>
              <Select.Option value={StoryboardProjectStatus.IN_PROGRESS}>
                进行中
              </Select.Option>
              <Select.Option value={StoryboardProjectStatus.COMPLETED}>
                已完成
              </Select.Option>
              <Select.Option value={StoryboardProjectStatus.ARCHIVED}>
                已归档
              </Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="项目标签"
            name="tags"
          >
            <Input placeholder="输入标签，用逗号分隔（可选）" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setEditModalVisible(false)
                form.resetFields()
                setCurrentProject(null)
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                保存修改
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default StoryboardPage